<?php

namespace tmcore\services\sms\driver;

use tmcore\services\sms\BaseSms;
use TencentCloud\Sms\V20190711\SmsClient;
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use tmcore\exceptions\MsgException;

/**
 * 腾讯云短信
 */
class Tencent extends BaseSms
{
    /**
     * 发送短信
     * @param array $params
     * @return mixed
     * @throws MsgException
     */
    public function sendSms(array $params)
    {
        try {
            $cred = new Credential($this->smsConfig['secretId'], $this->smsConfig['secretKey']);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);

            $client = new SmsClient($cred, 'ap-guangzhou', $clientProfile);
            $params = [
                'PhoneNumberSet'    => ['+86' . $this->mobile],
                'TemplateID'        => $this->templateCode,
                'Sign'              => $this->smsConfig['signName'],
                'TemplateParamSet'  => $this->getTemplateParam($params),
                'SmsSdkAppid'       => $this->smsConfig['appId'],
            ];
            $req = new SendSmsRequest();
            $req->fromJsonString(json_encode($params));
            $resp = json_decode($client->SendSms($req)->toJsonString(), true);
            if (isset($resp['SendStatusSet']) && $resp['SendStatusSet'][0]['Code'] == 'Ok') {
                return $resp;
            } else {
                $message = $res['SendStatusSet'][0]['Message'] ?? json_encode($resp);
                throw new \Exception('腾讯云短信错误：' . $message);
            }
        } catch(\Exception $e) {
            throw new MsgException('腾讯云短信错误：' . $e->getMessage());
        }
    }
}